/**
*
* @file sonar.c
*
* @brief Implementation of all the functions related to the Sonar
*
* @n @n CSc 460/560 Design and Analysis of Real Time Systems - Fall 2007
*
* @author Leanne Ross
* @author Clecio Varjao
*
*/

#include <avr/io.h>						// to access input and output port variables
#include <avr/interrupt.h>				// to access interrupt variables
#include <inttypes.h>					// defines integer functions
#include "../radio/radio.h"						// defines radio debugger functions
#include "sonar.h"						// defines sonar functions
#include "../common.h"
#include <util/delay.h>

static uint16_t time_falling = 0;		/**	holds time count when falling edge detected **/

void sonar_init(){
	/**	initialize sonar **/
	DDRC |= SONAR_PULSE_MASK;			/**	enable output on pin 6, port C **/
	DDRC &= ~_BV(PORTC7);
	TCCR3B &= ~(_BV(CS32) | _BV(CS30));	/**	set clock source to prescale by 8 **/
	TCCR3B |= _BV(CS31);				/**	set clock source to prescale by 8 **/
	TCCR3B |= _BV(ICNC3);				/**	enable noise cancelling **/

	/**	enable timer and global interrupts **/
	SET_RISING_EDGE();
	CLEAR_IC_FLAG();
	SET_IC_ENABLE();
	ENABLE_ECHO();

   //delay 250ms
   _delay_ms(250);
}

/**
*
* @brief Triggers Sonar
*
*/
void trigger_sonar() {
	ENABLE_PULSE();
	SET_RISING_EDGE();
	CLEAR_IC_FLAG();
	SET_IC_ENABLE();
}

/**
*
* @brief Read the distance
*
*/
uint8_t read_distance() {
	return (time_falling/US_PER_INCH);	/** pulse width = 147 us/inch **/
}

/**
*
* ISR function
*
*/
ISR(TIMER3_CAPT_vect) {
	DISABLE_PULSE();					/** only read one pulse at a time **/

	if (IS_RISING_EDGE()) {
		TCNT3 = 0;						/** reset timer counter for start of pulse **/
		SET_FALLING_EDGE();
		CLEAR_IC_FLAG();
	}
	else {
 		time_falling = ICR3;			/** ICR3 = TCNT3 when interrupt detected **/
		SET_RISING_EDGE();
		CLEAR_IC_FLAG();
	}
}
